// 请求控制
import axios, { type AxiosRequestConfig } from 'axios'

interface IRequestConfig extends AxiosRequestConfig {
  ignoreLoading?: boolean
}
interface IPending {
  url?: string
  method?: string
  params?: any
  data?: any
  cancel: () => void
}

// 用来控制相同请求在同一时间内只进行一次请求，根据需要进行
const pending: Map<string, IPending> = new Map()
export const addPending = (config: IRequestConfig) => {
  const { url, method, params, data } = config
  const key = `${url}_${method}_${JSON.stringify(params)}_${JSON.stringify(data)}`

  config.cancelToken = new axios.CancelToken((cancel) => {
    if (!pending.has(key)) {
      pending.set(key, { url, method, params, data, cancel })
    }
  })
}

export const removePending = (config: IRequestConfig) => {
  const { url, method, params, data } = config
  const key = `${url}_${method}_${JSON.stringify(params)}_${JSON.stringify(data)}`

  if (pending.has(key)) {
    const { cancel } = pending.get(key) as IPending
    cancel()
    pending.delete(key)
  }
}
